package  com.cn.adapters;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import cc.util.android.view.CCInnerListView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.FindCallback;
import com.nostra13.universalimageloader.core.ImageLoader;

import com.simu.constant.TableConstant;
import com.simu.constant.TableConstant.Collection;
import com.simu.constant.TableConstant.InsuranceBroker;
import com.simu.constant.TableConstant.User;
import com.simu.own.utils.T;
import com.simu.towercrane.R;
import com.simu.towercrane.activity.MainActivity;
import com.simu.towercrane.activity.ProductActivity;
import com.simu.towercrane.activity.PublicGroupsActivity;
import com.simu.towercrane.fragments.FragmentErShou;
import com.simu.towercrane.fragments.GlassesFragment;
import com.simu.towercrane.fragments.ProductFragment;
import comsimu.towercrane.video.util.Utils;

public class InsuranceImageAndTextListAdapter extends BaseAdapter {
	private String IMG_FILD = "ImageURL";
	private int mResID;
	private List<Map<String, Object>> mList;
	private ListView mListView;
	private ImageLoader mImageLoader;
	private LayoutInflater mInflater;
	private String[] mFrom;
	private int[] mTo;
    public  boolean refrsh=true;
	private Context mContext;
	private View viewcontext;
	private Map<String, Object> Mmap;
	/*
	 * private int[] mInvokedIDs; private OnClickListener[] mListeners;
	 */

	private int mBackgroundResID = -1;
	private LinkedHashMap<String, SoftReference<Bitmap>> lruCache;

	public InsuranceImageAndTextListAdapter(Context context,
			List<Map<String, Object>> list, int resourceid, String[] from,
			int[] to) {
	
		mContext=context;
		this.mList = list;
		this.mResID = resourceid;
		this.mFrom = from;
		this.mTo = to;
		
		mImageLoader = ImageLoader.getInstance();
		this.mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		lruCache = new LinkedHashMap<String, SoftReference<Bitmap>>(20, 0.75f, true) {
			private static final long serialVersionUID = -2920787383821401845L;

			@Override
			protected boolean removeEldestEntry(
					java.util.Map.Entry<String, SoftReference<Bitmap>> eldest) {
				boolean remove = size() > 20;
				if (remove) {
					SoftReference<Bitmap> soft = eldest.getValue();
					soft.clear();
				}
				return remove;
			}
		};
	}

	public void setListView(ListView listView) {
		this.mListView = listView;
	}

	public void setItemBackgroud(int resID) {
		this.mBackgroundResID = resID;
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Deprecated
	public void setImgFild(String fild) {
		this.IMG_FILD = fild;
	}



	@Override
	public View getView(int position, View convertView, ViewGroup parent) {		
		View v = null;		
	//因为重用布局会造成checkButton混乱，所以在这我就不重用布局了
	//猜测原因，重用布局的话会
    //卡顿原因没重用布局
	//xyb
	if (mListView instanceof CCInnerListView) {
			v = mInflater.inflate(mResID, parent, false);
		} else {
			if (convertView == null)
			{
				v = mInflater.inflate(mResID, parent, false);
				viewcontext=v;	
			}
			else 
			{
				v = convertView;
			viewcontext=v;
			}
		}
		//v = mInflater.inflate(mResID, parent, false);
		//viewcontext=v;
		bindView(mList.get(position), v);
		if (mBackgroundResID != -1)
			v.setBackgroundResource(mBackgroundResID);
		return v;
	}


	public void invokeListener(int[] ids, OnClickListener[] listeners) {
		/*
		 * this.mInvokedIDs = ids; this.mListeners = listeners;
		 */
	}

	@SuppressWarnings("unchecked")
	private void bindView(Map<String, Object> map, View v) {
		final int length = mFrom.length;				
		for (int i = 0; i < length; i++) {			
			final View view = v.findViewById(mTo[i]);
			if (view != null) {
				final Object data = map.get(mFrom[i]);
				String dataDe=data+"";
				if(view instanceof ImageView && view.getId()==R.id.collo_rb){
					if(dataDe.equals("true")){
						//((CheckBox)view).setChecked(true);
						((ImageView)view).setBackgroundResource(R.drawable.collected);
						//T.s(mContext, map.get("brokerName")+"check");
						//com.simu.own.utils.L.d(map.get("brokerName" )+"check");						
					}else{
						((ImageView)view).setBackgroundResource(R.drawable.collection);
					}
				}
				else if (view instanceof TextView) {									
					((TextView)view).setText(dataDe);
				} else if (view instanceof ImageView) {
					if(!dataDe.equals("")){
						Log.d("img", dataDe);
					}
					ImageView imageView = (ImageView)view;
					imageView.setTag(dataDe + "");
					SoftReference<Bitmap> soft = lruCache.get(dataDe + "");
					Bitmap bitmap = soft == null ? null : soft.get();
					if (bitmap != null) {
						//imageView.setImageBitmap(bitmap);
						BitmapDrawable bt=new BitmapDrawable(bitmap);
						imageView.setBackgroundDrawable(bt);
					} else {
						mImageLoader.displayImage(dataDe + "", imageView);
					}
				} else {
					Log.e("error",v.getClass().getName() + " is not a "
							+ " view that can be bounds by this SimpleAdapter");
				}
			}
		}
		//xyb
		onContentClick(v,map);
	}	
	
	@SuppressWarnings("unchecked")
	private void onContentClick(View convertView, final Map<String, Object> map) {
		// TODO Auto-generated method stub collo_im
		LinearLayout contactLayout=(LinearLayout) convertView.findViewById(R.id.contact_layout);
		ImageView colloRB= (ImageView) convertView.findViewById(R.id.collo_rb);
		//拨号
		contactLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String phoneString=map.get(TableConstant.InsuranceBroker.telNo)+"";
				Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phoneString));
				mContext.startActivity(intent);
			}
		});	
		//增加或删除联系人
		colloRB.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handlleData(map,v);		
			}
		});
	/*	colloRB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub	
				
					handlleData(map,isChecked,v);			
			}
		});*/
	}
	
	@SuppressWarnings("unchecked")
	public void handlleData(final Map<String, Object> map,final View v){
	    @SuppressWarnings("rawtypes")
		AVQuery query=AVQuery.getUserQuery();
	    SharedPreferences sPreferences=mContext.getSharedPreferences("user", Context.MODE_PRIVATE);
	    String userIdString=sPreferences.getString(Collection.userID,"");	   
	    query.whereEqualTo(User.objectId, userIdString);
	    query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> users, AVException e) {
				// TODO Auto-generated method stub
				if(e==null&&users!=null){
					AVObject user=users.get(0);
					AVRelation<AVObject> relation=user.getRelation(User.watchedInsuranceBroker);					
					AVObject insuranStrokerObject=(AVObject)(map.get(InsuranceBroker.self));
					String checked=map.get(TableConstant.watched)+"";	
					if(checked.equals("false")){						
						map.put(TableConstant.watched,"true");
						v.setBackgroundResource(R.drawable.collected);
						relation.add(insuranStrokerObject);					
					}else{
						//T.s(mContext, insuranStrokerObject.getString("brokerName")+"delete");					
						map.put(TableConstant.watched,"false");	
						v.setBackgroundResource(R.drawable.collection);
						relation.remove(insuranStrokerObject);
					}
					user.saveInBackground();
				}
			}
		});
	    
	}
}
